from django.shortcuts import render,redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from blog.models import BlogModel,CnblogsModel,JobbleModel,CSDNModel,CategoryModel,AuthorModel
from django.core.paginator import Paginator
from django.db.models import Q
# Create your views here.
def index(request):
    # 分页查询，分类查询的操作，来源查询的操作
    # 查询文章列表
    blog_query=BlogModel.objects
    print(blog_query.filter(fbrq__day=1))
    print([item.day for item in blog_query.filter(fbrq__day=1)])
    category=request.GET.get('category',0)
    if category=='':
        category=0
    source=request.GET.get('source',0)
    if source=='':
        source=0
    search=request.GET.get('search','')
    if search:
        result=CategoryModel.objects.filter(name=search).first()
        if result:
            category=result.id
        else:
            result=AuthorModel.objects.filter(name=search).first()
            if result:
                source=result.id
            else:
                blog_query=blog_query.filter(Q(title__icontains=search)|Q(contents__icontains=search))
    if category and category!='0':
        blog_query=blog_query.filter(category=category)
    if source and source!='0':
        blog_query=blog_query.filter(author=source)
    paginator=Paginator(blog_query.all(),10)
    page=request.GET.get('page',1)
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)
    # 分类的列表
    category_list=CategoryModel.objects.all()
    # 作者的列表
    author_list=AuthorModel.objects.all()
    page_pre_have=False
    page_next_have=False
    if contacts.number <=5:
        page_count_list=list(range(1, min(5+1,paginator.num_pages+1)))
        if contacts.number+5<paginator.num_pages:
            page_next_have=True
    elif contacts.number+5>paginator.num_pages:
        page_count_list=list(range(paginator.num_pages-5,paginator.num_pages+1))
        if contacts.number-5>0:
            page_pre_have=True
    else:
        page_next_have=True
        page_pre_have=True
        page_count_list=list(range(contacts.number - 2, contacts.number + 3))
    context={'category_list':category_list,'author_list':author_list,'blog_list':contacts.object_list,'page':contacts,'page_count':page_count_list,'page_pre_have':page_pre_have,'page_next_have':page_next_have,'category':int(category),'source':int(source),'search':search}
    return render(request,'index.html',context=context)

def blog(request,id):
    blog_obj=BlogModel.objects.get(id=id)
    if blog_obj:
        context = {'blog': blog_obj,'labels':blog_obj.labels.split(',')}
        return render(request,'sidebar.html',context=context)
    else:
        return redirect('/')